<template>
  <div>
    <el-card>
      <div slot="header">
        <span>账号列表</span>
      </div>
      <div class="content">
        <el-table
          :data="tableData"
          :style="{ width: w + 'px' }"
          ref="accTab"
          @selection-change="tableSelected"
        >
          <!-- 双向绑定style样式 -->

          <!-- 表格 -->
          <!-- :xxx="xxx"  绑定数据 -->
          <!-- type="selection"  设置勾选框 -->
          <el-table-column type="selection"> </el-table-column>

          <el-table-column prop="account" label="账号" sortable>
          </el-table-column>

          <el-table-column
            prop="userGroup"
            label="用户组"
            sortable
          ></el-table-column>

          <el-table-column label="创建时间" sortable prop="ctime">
            <template slot-scope="scope"
              ><span>{{ scope.row.ctime | formatDate }} </span></template
            > </el-table-column
          ><!-- 传参渲染 -->

          <el-table-column label="操作" width="180">
            <!-- 设置两个按钮的宽度 -->
            <template slot-scope="scope">
              <!-- slot-scope="scope"  作用域插槽 -->
              <!-- scope.$index  拿索引 -->
              <!-- scope.row   拿当前行的数据-->

              <!-- 编辑按钮 -->
              <el-button
                size="mini"
                @click="handleEdit(scope.$index, scope.row)"
                icon="el-icon-edit"
              ></el-button>

              <!-- 删除按钮 -->
              <el-button
                size="mini"
                type="danger"
                @click="handleDelete(scope.row.id)"
                icon="el-icon-delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <!--  :page-size="pageSize"  每页条数 -->
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          background
        >
        </el-pagination>

        <el-button size="small" type="danger" @click="deleAll"
          >批量删除</el-button
        >
        <el-button size="small" type="primary" @click="cancelSelected"
          >取消选择</el-button
        >
      </div>

      <!-- 编辑模态框 -->
      <el-dialog
        title="修改账号"
        :visible.sync="dialogFormVisible"
        width="480px"
      >
        <el-form :model="editForm" :rules="rules" ref="addAccForm">
          <el-form-item
            label="账号"
            :label-width="formLabelWidth"
            prop="account"
          >
            <el-input
              v-model="editForm.account"
              autocomplete="off"
              placeholder="请修改账号"
              clearable
              size="small"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="用户分组"
            :label-width="formLabelWidth"
            prop="userGroup"
          >
            <el-select
              v-model="editForm.userGroup"
              placeholder="请选择账号分组"
              size="small"
            >
              <el-option label="普通管理员" value="普通管理员"></el-option>
              <el-option label="超级管理员" value="超级管理员"></el-option>
              <el-option label="普通用户" value="普通用户"></el-option>
              <el-option label="体验用户" value="体验用户"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false" size="small"
            >取 消</el-button
          >
          <el-button type="primary" @click="saveEditData" size="small"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      
    </el-card>
  </div>
</template>

<script>
import { usersList, usersDel, usersEdit, batchDel } from "@/api/user"; //{usersList}---导入/api/user里面的usersList
import dayjs from "dayjs"; //时间处理库
export default {
  data() {
    return {
      dialogFormVisible: false, //控制模态框隐藏
      editForm: {}, //修改表单数据
      formLabelWidth: "80px", //表单宽度
      ids: [], //批量删除的id
      rules: {
        //账号的
        account: [
          // message  提示输入账户
          { required: true, message: "请输入账号", trigger: "change" },
          { required: true, message: "请输入账号", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符", //错误提示
            trigger: "blur", //失去焦点触发
          },
        ],
        userGroup: [
          { required: true, message: "请选择用户组", trigger: "blur" },
        ],
      },
      currentPage: 1, //当前页
      total: 0, //页面总条数
      pageSize: 5, //每页显示的条数
      w: document.body.clientWidth - 200 - 20 - 40, //设置的表格宽度
      //获取浏览器的宽度-左侧菜单宽度-右侧内边距
      tableData: [
        //账户列表
        // {
        //   id: 1,
        //   account: "周杰伦",
        //   userGroup: "超级管理员",
        //   ctime: "2022-12-04",
        // },
      ],
    };
  },
  methods: {
    //方法

    //批量删除
     deleAll() {
      if (this.ids.length > 0) {
        this.$confirm("此操作将删除选中账号, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(async() => {
            let res = await batchDel({ ids: this.ids });
            let { code, msg } = res;
            if (code === 0) {
              this.$message({
                type: "success",
                message: msg,
              });
              this.loadData(); //重新加载数据
            } else {
              this.$message.error(msg);
            }
          })
          .catch(() => {
            // console.log("取消批量删除了");
          });
      }
    },
    //多选框选中
    tableSelected(selection) {
      // console.log(selection);//打印结果是选择的账户属性
      this.ids = selection.map((item) => item.id); //定义保存
      //  console.log(this.ids)//打印结果是选择的账户属性里面的id
    },

    //取消选择
    cancelSelected() {
      this.$refs.accTab.clearSelection();
    },
    //编辑
    handleEdit(index, row) {
      // console.log(row, index);
      this.dialogFormVisible = true; //显示模态框

      this.editForm = { ...row }; //浅拷贝解决地址一样

      // row--对象 --当行数据
    },
    //确定修改账号的函数
    async saveEditData() {
      let res = await usersEdit(this.editForm);
      let { code, msg } = res;
      if (code === 0) {
        this.$message({
          type: "success",
          message: msg,
        });
        this.loadData(); //重新加载数据
      } else {
        this.$message.error(msg);
      }

      this.dialogFormVisible = false; //隐藏模态框
      this.$refs.addAccForm.resetFields(); //清空验证
    },

    //删除
    handleDelete(id) {
      this.$confirm("此操作将删除该账号, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await usersDel({ id }); //删除账号接口
          let { code, msg } = res;
          if (code === 0) {
            this.$message({
              type: "success",
              message: msg,
            });
          } else {
            this.$message.error(msg);
          }

          this.loadData(); //重新刷新
        })
        .catch(() => {
          // console.log("已取消删除");
        });
    },
    //触发窗口函数
    resizeHandle() {
      // console.log("窗口发生了改变了.亲");
      this.w = document.body.clientWidth - 300;
    },
    //---------------------分页-----------
    // 每一页条数改变触发
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val; //pageSize---每页条数
      this.loadData(); //重新刷新
    },
    //当前页改变触发
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val; //currentPage---当前页
      this.loadData(); //重新刷新
    },

    //---------------------------------
    //获取账号列表的函数
    async loadData() {
      let res = await usersList({
        currentPage: this.currentPage, //currentPage---当前页
        pageSize: this.pageSize, //pageSize---每页条数
      });
      let { total, data } = res;
      // console.log(res );
      this.total = total; //渲染页面总条数
      this.tableData = data; //渲染账户列表
    },
  },

  //生命周期
  created() {
    //resize窗口大小发生改变触发的事件
    window.addEventListener("resize", this.resizeHandle);

    //调用获取列表数据的函数
    this.loadData();
  },
  beforeDestroy() {
    //页面销毁之前 注销窗口事件
    window.removeEventListener("resize", this.resizeHandle);
  },

  //过滤器
  filters: {
    formatDate(val) {
      return dayjs(val).format("YYYY/MM/DD");
    },
  },
};
</script>


<style lang="less" scoped>
//scoped 让样式私有化,对当前组件生效
//1. scoped 只在当前页组件生效 让代码私有化
//2. element的分页相当于其他页面,所以在当前页面添加scoped的样式不能用到其他组件
//3. 可以再加个不带scoped的style
//4. 穿透  /deep/
.el-pagination {
  margin: 20px 0;
}

// 穿透 突破scoped的限制
/deep/.el-pager {
  .active {
    background-color: rgb(250, 176, 66) !important;
  }
}
/deep/.el-dialog__body {
  padding: 40px 40px 20px 30px;
  // background-color: rgb(170, 33, 33);
}
.dialog-footer {
  margin-right: 22px;
}
.el-select {
  width: 100%;
}
</style>